import { Component, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd/modal';
import { storageDeliveryMethodArrs } from '../../xstorage-manage-pipes/storage-manage-z.pipe';
import { storageAllocationStateArrs } from '../../xstorage-manage-pipes/storage-manage-z.pipe';
import { CommonService } from '../../../../services-common/common.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { PermissionService } from '../../../../service/permission.service';
import { StorageTransferOrderService } from '../../xstorage-manage-services/storage-transfer-order.service';

@Component({
  selector: 'app-storage-transfer-list',
  templateUrl: './storage-transfer-list.component.html',
  styleUrls: ['./storage-transfer-list.component.scss']
})
export class StorageTransferListComponent implements OnInit {
  // 路由缓存恢复时
  static updateCache: any = null;
  @ViewChild('followUpRef') followUpRef: any;

  tabVal: number = 0;
  searchOptions: any = [
    { type: 1, labelText: '单号', valueKey: 'allocationNumber', value: '' },
    { type: 1, labelText: '包含商品', valueKey: 'goods', value: '', placeholder: '编码/69码/名称' },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'states',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [...storageAllocationStateArrs],
    },
    {
      type: 2,
      labelText: '调拨类型',
      valueKey: 'types',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'content', label: 'name' },
      selectOptions: [],
    },
    {
      type: 2,
      labelText: '出库仓库',
      valueKey: 'deliveryWhIds',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'id', label: 'name' },
      selectOptions: [],
    },
    {
      type: 2,
      labelText: '入库仓库',
      valueKey: 'warehousingWhIds',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'id', label: 'name' },
      selectOptions: [],
    },
    { type: 3, labelText: '新建时间', valueKey: ['beginTime', 'endTime'], value: [], isTimeSelect: true }
  ];
  searchParams: any = {};

  storeOptions: any[] = []; // 仓库Options
  allocationTypeOptions: any = []; // 调拨类型Options
  logisticsOptions: any[] = []; // 物流Options

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  // 跟进 Modal
  initParams: any = {
    type: 5, // type  1、采购 2、SN 3、入库单 4、出库单 5、调拨单
    relationInformation: ''
  };

  /**
   * 审核 Modal
   * ----------------------------------------------------------------
   */
  isExamineVisible = false;
  examineLoading = false;
  examineItem: any = {};
  auditOpinion: string = '';

  /**
   * 作废 Modal
   * ----------------------------------------------------------------
   */
  isZfVisible = false;
  submitZfLoading = false;
  toVoidItem: any = {};
  toVoidRemark = ''; // 作废备注

  /**
   * 完善出库信息 Modal
   * ----------------------------------------------------------------
   */
  isDeliveryVisible = false;
  deliveryOptions: any[] = [...storageDeliveryMethodArrs];
  outItem: any = {};
  validateDeliveryForm!: FormGroup;

  /**
   * ----------------------------------------------------------------
   * table check
   * ---------------------------------------------------------------- 
   */

  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id)) && this.listOfCurrentPageData.length > 0;
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  constructor(
    private msg: NzMessageService,
    private fb: FormBuilder,
    private commonService: CommonService,
    private modal: NzModalService,
    public permission: PermissionService,
    private storageCommonService: StorageCommonService,
    private services: StorageTransferOrderService
  ) { }

  ngOnInit(): void {
    this.loadLogisticsData();
    this.loadStoreOptions();
    this.loadAllocationTypeOptions();
    // 完善出库信息
    this.validateDeliveryForm = this.fb.group({
      isFreight: ['', [Validators.required]], // 运费承担 0我司承担 1用户承担
      deliveryMethod: ['', [Validators.required]], // 配送方式
      expressCode: [''], // 物流公司
      expressNo: [''], // 物流单号
      expressPrice: [''], // 运费
      deliverRemark: [''] // 发货备注
    });

    StorageTransferListComponent.updateCache = () => {
      this.loadLogisticsData();
      this.loadStoreOptions();
      this.loadAllocationTypeOptions();
      this.loadTable();
    }
  }

  // 调拨类型Options
  async loadAllocationTypeOptions() {
    const res = await this.commonService.getDictList('allocation_type');
    this.allocationTypeOptions = res || [];
    this.setSearchOption(res, 'types');
  }

  // 查询仓库Options
  async loadStoreOptions() {
    let params = {
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.storeOptions = data.records || [];
      this.setSearchOption(data.records, 'deliveryWhIds'); // 出库仓库
      this.setSearchOption(data.records, 'warehousingWhIds'); // 入库仓库
    } else {
      this.msg.error(message);
    }
  }

  // 查询物流
  async loadLogisticsData() {
    const res: any = await this.commonService.getDictList('logistics_company');
    this.logisticsOptions = res || [];
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getAllocationList(params);
    this.tableParams.loading = false;
    // return

    if (code === 0) {
      this.tableParams.tableData = data.records || [];
      this.tableParams.total = data.total || 0;
    } else {
      this.msg.error(message);
    }
  }

  queryData(params: any) {
    this.searchParams = params;

    this.setOfCheckedId.clear();
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData(params: any) {
    this.searchParams = params;
    this.tabVal = 0;

    this.setOfCheckedId.clear();
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  /**
   * 删除
   * @param item 
   */
  async deleteItem(item: any) {
    const {code, message}: any = await this.services.deleteAllocationData({id: item.id});
    if (code === 0) {
      this.msg.success('删除成功');
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  // 审核等interface
  async commonAuditInterface(params: any, type: number) {
    let datas = {
      ...params,
      state: type
    }
    const {code, data, message}: any = await this.services.allocationExamineData(datas);

    if (code === 0) {
      this.msg.success(data);
      this.setOfCheckedId.clear();
      this.isDeliveryVisible = false;
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 提交审核
   */
  submitReview(item: any) {
    let params = {
      ids: [item.id],
      note: ''
    }
    this.commonAuditInterface(params, 1);
  }

  /**
   * ----------------------------------------------------------------
   * 审核
   * ----------------------------------------------------------------
   */
  showExamineModal(item: any) {
    this.examineItem = item;
    this.auditOpinion = '';
    this.isExamineVisible = true;
  }

  async subExamine(type: number) {
    if (type === 8 && this.commonService.isEmpty(this.auditOpinion)) {
      this.msg.warning('请输入审核意见');
      return
    }

    let params = {
      ids: [this.examineItem.id],
      state: type,
      note: this.auditOpinion
    }
    this.examineLoading = true;
    const res: any = await this.services.allocationExamineData(params);
    this.examineLoading = false;

    if (res.code === 0) {
      this.isExamineVisible = false;
      this.msg.success('操作成功');
      this.loadTable();
    } else {
      this.msg.error(res.message);
    }
  }

  /**
   * 通知出库
   */
  noticeOutStore(item: any) {
    let params = {
      ids: [item.id],
      note: ''
    }
    this.commonAuditInterface(params, 3);
  }

  /**
   * 通知入库
   */
  noticeWarehousStore(item: any) {
    let params = {
      ids: [item.id],
      note: ''
    }
    this.commonAuditInterface(params, 5);
  }

  /**
   * 入库完毕
   */
  warehousCompleted(item: any) {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认后单据将彻底调拨完成并且不可操作，该操作不可逆，确认已经入库完毕?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        let params = {
          ids: [item.id],
          note: ''
        }
        this.commonAuditInterface(params, 6);
      },
      nzCancelText: '取消'
    });
  }

  /**
   * ----------------------------------------------------------------
   * 作废 Modal
   * ----------------------------------------------------------------
   */
  showTovoidModal(item?: any) {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请先选择所需操作项');
      return
    }

    this.toVoidRemark = '';
    this.isZfVisible = true;
  }

  async submitToVoidData() {
    if (this.commonService.isEmpty(this.toVoidRemark)) {
      this.msg.warning('请输入备注');
      return
    }

    let params = {
      ids: [...this.setOfCheckedId],
      state: 7, // 作废
      note: this.toVoidRemark
    }
    // return
    this.submitZfLoading = true;
    const {code, data, message}: any = await this.services.allocationExamineData(params);
    this.submitZfLoading = false;

    if (code === 0) {
      this.isZfVisible = false;
      this.setOfCheckedId.clear();
      this.msg.success(data);
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 完善出库信息 Modal
   * ----------------------------------------------------------------
   */
  showEditDeliveryModal(item: any) {
    this.validateDeliveryForm.reset();
    this.outItem = item;

    if (item.differentQuantity > 0) {
      this.modal.confirm({
        nzTitle: '确认出库',
        nzContent: `有${item.differentQuantity}个商品的实际出库数量和预计出库数量不一致。确认出库数量不一致吗?`,
        nzOkText: '确认',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: () => {
          this.isDeliveryVisible = true;
        },
        nzCancelText: '取消'
      });
    } else {
      this.isDeliveryVisible = true;
    }
  }

  subEditDeliveryData() {
    if (this.validateDeliveryForm.valid) {
      let wlObj: any = this.logisticsOptions.find(item => item.content === this.validateDeliveryForm.value.expressCode);
      let params = {
        ...this.validateDeliveryForm.value,
        expressName: wlObj?.name || '',
        ids: [this.outItem.id]
      }

      for (let key in params) {
        if (this.commonService.isEmpty(params[key])) {
          params[key] = '';
        }
      }
      this.commonAuditInterface(params, 4);
    } else {
      Object.values(this.validateDeliveryForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * other
   * ----------------------------------------------------------------
   */
  setSearchOption(array: Array<any>, val: string) {
    let temIndex = this.searchOptions.findIndex((item: any) => item.valueKey === val);
    this.searchOptions[temIndex].selectOptions = array || [];
  }

  // Filter Text
  filterText(arrs: Array<any>, keyVal: any, idKey: string) {
    let tempObjs: any = {};
    if (arrs.length) {
      tempObjs = arrs.find(item => item[idKey] == keyVal);
    }

    return tempObjs?.name || '-';
  }

  tabChange(val: any) {
    // 未结束 == 除(草稿/调拨完成/已作废)之外状态
    let temIndex = this.searchOptions.findIndex((item: any) => item.valueKey === 'states');
    this.searchOptions[temIndex].value = val === 1 ? [1, 2, 3, 4, 5] : [];
    this.searchParams.states = val === 1 ? '1,2,3,4,5' : '';

    this.tableParams.page = 1;
    this.loadTable();
  }

  // 跟进
  showFollowModal(item: any) {
    this.initParams.relationInformation = item.id;
    this.followUpRef.isModelVisible = true;
  }
}
